package com.smart.car.message.job;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.smart.car.common.res.entity.MemberUser;
import com.smart.car.common.res.exception.BusinessException;
import com.smart.car.message.feign.MemberServiceFeign;
import com.smart.car.message.service.MessageInfoService;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 分布式定时任务
 *
 * @author zoutao.blog.csdn.net
 * @date 2021/5/10
 */
@Slf4j
@Component
public class UserBirthdayBasedPushJob {

    //单体应用下的定时任务-每隔5s输出一次日志
    //@Scheduled(cron = "0/5 * * * * ?")
    public void scheduledTask() {
        log.info("单体应用类的定时任务正在运行...>>>>>>"  + LocalDateTime.now());
    }


    @Autowired
    private MemberServiceFeign memberService;
    @Autowired
    private MessageInfoService messageService;

    //分布式应用下的定时任务-每隔5s输出一次日志(真实应用下，改为每天运行一次即可)
    @Scheduled(cron = "0/5 * * * * ?")
    @SchedulerLock(name = "birthdayMarketingJob")
    public void scheduledTaskFBS() {
        try {
            String members = memberService.listFeign();
            List<MemberUser> array  = JSONArray.parseArray(members, MemberUser.class);
            //改用2021-05-10格式
            String today= DateUtil.today();
            log.info("生日时间是:{}",today);
            for (MemberUser one : array) {
                //推送当天生日祝福短信
                if (today.equals(one.getBirth())) {
                    log.info("发送短信给:>>>>>>>>>>>>>> " + one.getPhone());
                    String phoneNum  = one.getPhone();
                    // 调用业务层接口 发送短信服务
                    String code  = String.valueOf(Math.random()).substring(3, 7);
                    boolean sendSmsFlag = messageService.sendSmsByTx(phoneNum, code, 5L);
                    log.info("生日或营销短信推送成功否？{}",sendSmsFlag);
                }
            }
        } catch (BusinessException e) {
            log.error("定时生日短信任务异常 " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("分布式应用下的定时任务正在运行..."  + LocalDateTime.now());
    }
}
